<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="hasPermission('user:add')"
          type="primary" 
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="users" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button 
              v-if="hasPermission('user:edit')"
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="hasPermission('user:assign-role')"
              type="warning" 
              size="small" 
              @click="handleAssignRole(row)"
            >
              分配角色
            </el-button>
            <el-button 
              v-if="hasPermission('user:delete')"
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="userDialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="500px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeUserDialog">取消</el-button>
        <el-button type="primary" @click="confirmUser" :loading="userLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="assignRoleVisible" title="分配角色" width="500px">
      <div class="assign-role-content">
        <div class="user-info">
          <span>用户：{{ assignRoleForm.nickname }}（{{ assignRoleForm.username }}）</span>
        </div>
        <el-form label-width="80px">
          <el-form-item label="选择角色">
            <el-checkbox-group v-model="selectedRoles">
              <el-checkbox 
                v-for="role in allRoles" 
                :key="role.id" 
                :label="role.id"
              >
                {{ role.roleName }}（{{ role.roleCode }}）
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeAssignDialog">取消</el-button>
        <el-button type="primary" @click="confirmAssignRole" :loading="assignLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 外键约束处理组件 -->
    <ForeignKeyHandler
      ref="foreignKeyHandlerRef"
      v-model:visible="foreignKeyVisible"
      :entity-type="'user'"
      :entity-name="currentDeleteUser?.username || ''"
      :error-message="'用户存在关联数据，无法直接删除'"
      :related-data="[]"
      :on-resolve="handleForeignKeyResolve"
      @resolved="foreignKeyVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '../utils/request'
import { usePermissions } from '../stores/permission'
import ForeignKeyHandler from '../components/ForeignKeyHandler.vue'

const { hasPermission } = usePermissions()

const users = ref([])
const loading = ref(false)
const userDialogVisible = ref(false)
const userLoading = ref(false)
const isEdit = ref(false)
const userFormRef = ref()
const assignRoleVisible = ref(false)
const assignLoading = ref(false)
const allRoles = ref([])
const selectedRoles = ref([])

// 外键处理相关
const foreignKeyHandlerRef = ref()
const foreignKeyVisible = ref(false)
const currentDeleteUser = ref(null)

const userForm = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  status: 1
})

const assignRoleForm = reactive({
  userId: null,
  username: '',
  nickname: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/users')
    users.value = response.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有角色
const fetchAllRoles = async () => {
  try {
    const response = await request.get('/admin/roles')
    allRoles.value = response.data
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  resetUserForm()
  userDialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    email: row.email,
    phone: row.phone,
    status: row.status
  })
  userDialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.nickname}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/admin/users/${row.id}`)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      
      // 检查是否是外键约束错误
      if (error.response?.data?.data?.entityType === 'user') {
        currentDeleteUser.value = row
        foreignKeyVisible.value = true
      } else {
        ElMessage.error('删除失败：' + (error.response?.data?.message || error.message))
      }
    }
  }
}

// 处理外键约束解决方案
const handleForeignKeyResolve = async (resolution) => {
  try {
    const user = currentDeleteUser.value
    
    switch (resolution.action) {
      case 'soft_delete':
        // 软删除：直接调用删除接口（后端已经是软删除）
        await request.delete(`/admin/users/${user.id}`)
        ElMessage.success('用户已禁用')
        break
        
      case 'cascade_delete':
        // 级联删除：调用特殊的级联删除接口
        await request.delete(`/admin/users/${user.id}?cascade=true`)
        ElMessage.success('用户及关联数据已删除')
        break
        
      default:
        throw new Error('不支持的解决方案')
    }
    
    fetchUsers()
  } catch (error) {
    console.error('处理外键约束失败:', error)
    throw error
  }
}

// 分配角色
const handleAssignRole = async (row) => {
  assignRoleForm.userId = row.id
  assignRoleForm.username = row.username
  assignRoleForm.nickname = row.nickname
  
  try {
    // 获取用户当前角色
    const response = await request.get(`/admin/users/${row.id}/roles`)
    selectedRoles.value = response.data.map(role => role.id)
    assignRoleVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户角色失败')
  }
}

// 确认保存用户
const confirmUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    userLoading.value = true
    
    if (isEdit.value) {
      await request.put(`/admin/users/${userForm.id}`, userForm)
      ElMessage.success('更新成功')
    } else {
      await request.post('/admin/users', userForm)
      ElMessage.success('创建成功')
    }
    
    closeUserDialog()
    fetchUsers()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    userLoading.value = false
  }
}

// 确认分配角色
const confirmAssignRole = async () => {
  try {
    assignLoading.value = true
    await request.post(`/admin/users/${assignRoleForm.userId}/roles`, selectedRoles.value)
    ElMessage.success('角色分配成功')
    closeAssignDialog()
  } catch (error) {
    ElMessage.error('角色分配失败')
  } finally {
    assignLoading.value = false
  }
}

// 关闭用户对话框
const closeUserDialog = () => {
  userDialogVisible.value = false
  resetUserForm()
}

// 关闭分配角色对话框
const closeAssignDialog = () => {
  assignRoleVisible.value = false
  selectedRoles.value = []
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: null,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    status: 1
  })
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

onMounted(() => {
  fetchUsers()
  fetchAllRoles()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.assign-role-content {
  padding: 10px 0;
}

.user-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-weight: 500;
}

.el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style> 